package com.onesports.intelligent.k12.polarlight.security.jwt;

import com.onesports.framework.kit.common.util.ParamUtils;
import com.onesports.intelligent.k12.polarlight.security.DomainUserDetails;
import com.onesports.intelligent.k12.polarlight.security.TokenProvider;
import com.onesports.intelligent.k12.polarlight.security.wx.WxAuthenticationToken;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author aj
 */
@Component
public class JwtTokenProvider implements TokenProvider {

    private final Logger log = LoggerFactory.getLogger(JwtTokenProvider.class);

    private static final String AUTHORITIES_KEY = "auth";

    private static final String ID_KEY = "current";

    private static final String ORGANIZATION_ID_KEY = "organization";

    private static final String STAFF_ID_KEY = "staff";

    private static final String PHONE_KEY = "phone";

    private static final String SYSTEM_CODE_KEY = "system";

    private final Key key;

    private final JwtParser jwtParser;

    private final long tokenValidityInMilliseconds;

    private final long tokenValidityInMillisecondsForRememberMe;

    public JwtTokenProvider(JHipsterProperties jHipsterProperties) {
        byte[] keyBytes;
        String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret();
        if (!ObjectUtils.isEmpty(secret)) {
            log.debug("Using a Base64-encoded JWT secret key");
            keyBytes = Decoders.BASE64.decode(secret);
        } else {
            log.warn(
                    "Warning: the JWT key used is not Base64-encoded. " +
                            "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."
            );
            secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
            keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        }
        key = Keys.hmacShaKeyFor(keyBytes);
        jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
        this.tokenValidityInMilliseconds = 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
        this.tokenValidityInMillisecondsForRememberMe =
                1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe();
    }

    @Override
    public String createToken(Authentication authentication, String prefix, boolean rememberMe) {
        String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","));
        long now = (new Date()).getTime();
        Date validity;
        if (rememberMe) {
            validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
        } else {
            validity = new Date(now + this.tokenValidityInMilliseconds);
        }
        DomainUserDetails principal = (DomainUserDetails) authentication.getPrincipal();
        return Jwts
                .builder()
                .setSubject(principal.getNickname())
                .claim(ID_KEY, principal.getCurrent())
                .claim(ORGANIZATION_ID_KEY, principal.getOrganizationId())
                .claim(STAFF_ID_KEY, principal.getStaffId())
                .claim(PHONE_KEY, principal.getPhone())
                .claim(SYSTEM_CODE_KEY, principal.getSystemCode())
                .claim(AUTHORITIES_KEY, authorities)
                .signWith(key, SignatureAlgorithm.HS512)
                .setExpiration(validity)
                .compact();
    }

    @Override
    public Boolean refreshExpiration(String token, String loginUserId) {
        return false;
    }

    @Override
    public Authentication getAuthentication(String token) {
        Claims claims = jwtParser.parseClaimsJws(token).getBody();

        Collection<? extends GrantedAuthority> authorities = Lists.newArrayList();
        if (ParamUtils.isNotEmpty(claims.get(AUTHORITIES_KEY))) {
            authorities = Arrays
                    .stream(claims.get(AUTHORITIES_KEY).toString().split(","))
                    .filter(auth -> !auth.trim().isEmpty())
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }

        DomainUserDetails principal = DomainUserDetails.builder()
                .current(String.valueOf(claims.get(ID_KEY)))
                .username(claims.getSubject())
                .nickname(claims.getSubject())
                .organizationId(String.valueOf(claims.get(ORGANIZATION_ID_KEY)))
                .staffId(String.valueOf(claims.get(STAFF_ID_KEY)))
                .phone(claims.get(PHONE_KEY) != null ? String.valueOf(claims.get(PHONE_KEY)) : "")
                .systemCode(claims.get(SYSTEM_CODE_KEY) != null ? String.valueOf(claims.get(SYSTEM_CODE_KEY)) : "")
                .authorities(authorities)
                .build();

        return new WxAuthenticationToken(principal, authorities);
    }

    @Override
    public boolean validateToken(String authToken) {
        try {
            jwtParser.parseClaimsJws(authToken);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            log.info("Invalid JWT token.");
            log.trace("Invalid JWT token trace.", e);
        }
        return false;
    }
}
